<template>
  <div>
    <a-page-header :ghost="false" title="阅卷管理/THE MARKING MANAGEMENT" />
    <a-card
      :bordered="false"
      style="margin-left: 16px;margin-right: 16px;margin-top: 16px;"
    >
      <p class="notice">
        阅卷说明：由于客观题答案特殊，因此需要老师自己判卷。
      </p>
    </a-card>
    <a-card
      :bordered="false"
      style="margin-left: 16px;margin-right: 16px;margin-top: 16px;"
    >
      <a-card :bordered="false">
        <a-row :gutter="16">
          <a-col :span="20">
            <a-form-model layout="inline">
              <a-form-model-item label="考试名称">
                <a-input placeholder="请输入考试名称" v-model="markName" />
              </a-form-model-item>
              <a-form-model-item>
                <a-button type="primary" @click="findMarkPaper">
                  搜索
                </a-button>
              </a-form-model-item>
              <a-form-model-item>
                <a-button @click="resetSearch">
                  重置
                </a-button>
              </a-form-model-item>
            </a-form-model>
          </a-col>
        </a-row>
      </a-card>
      <a-table
        style="margin-top: 16px;"
        tableLayout="auto"
        :columns="columns"
        :data-source="data"
      >
        <span slot="name" slot-scope="text">{{ text }}</span>
        <span slot="questionTitle">考试名称</span>
        <!-- <span slot="action" slot-scope="text,index"> -->
        <template slot="action" slot-scope="text, record">
          <span slot="action">
            <a @click="showMarkingModal(record)">开始阅卷</a>
          </span>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model="examVisible"
      :title="
        '阅卷【注意：中途不进行阅卷请一定要“提交”，否则不会进行保存】 ' +
          (list.length == 0 ? '' : '已阅卷：' + (idx + 1) + '/' + list.length)
      "
      okText="完成"
      cancelText="取消"
      :maskClosable="false"
      :destroyOnClose="true"
      :width="1080"
    >
      <a-spin :spinning="spinning"> </a-spin>
      <div v-if="spinning == false">
        <div v-if="list.length != 0">
          <div class="notice">题目名称：{{ list[idx].info.name }}</div>
          <div v-if="list[idx].info.questionImgs[0] != ''" style="width:100%;">
            <div v-for="(imgs, idx) in list[idx].info.questionImgs" :key="idx">
              <div
                class="media questionImg"
                style="width:150px;height:150px;float:left;"
              >
                <a
                  href="#"
                  class="media-content"
                  @click="showImg(imgs)"
                  :style="{ 'background-image': 'url(' + imgs + ')' }"
                ></a>
              </div>
            </div>
            <div style="clear:both"></div>
          </div>

          <a-modal
            :visible="previewVisible"
            :footer="null"
            @cancel="handleCancel"
          >
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
          <div style="font-size:16px;margin-top:16px;">
            本题分值：<a-tag color="#108ee9" style="font-size:18px">
              {{ list[idx].info.score }}
            </a-tag>
          </div>
          <div style="font-size:16px;margin-top:16px;">
            学生答案：{{ list[idx].answer }}
          </div>
          <div style="font-size:16px;margin-top:16px;">
            得分：
            <a-input-number
              v-model="form[list[idx].i].data[list[idx].j].score"
              :min="0"
              :max="list[idx].info.score"
            />
          </div>
        </div>
        <div v-else>
          <a-result title="目前还不需要阅卷～">
            <template #icon>
              <a-icon type="smile" theme="twoTone" />
            </template>
          </a-result>
        </div>
      </div>

      <template slot="footer">
        <a-button
          @click="idx > 0 ? --idx : $message.warning('这已经是第一题了')"
        >
          上一题
        </a-button>
        <a-button
          type="primary"
          @click="
            idx < list.length - 1
              ? ++idx
              : $message.warning('这已经是最后一题了')
          "
        >
          下一题
        </a-button>
        <a-button type="primary" @click="postMark">
          提交
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
const columns = [
  {
    dataIndex: "name",
    key: "name",
    slots: { title: "questionTitle" },
    scopedSlots: { customRender: "name" }
  },
  {
    title: "考试班级",
    dataIndex: "examClasses",
    key: "examClasses"
  },
  {
    title: "总分",
    key: "examTotalScore",
    dataIndex: "examTotalScore"
  },
  {
    title: "开始时间",
    dataIndex: "examStartT",
    key: "examStartT"
  },
  {
    title: "结束时间",
    dataIndex: "examEndT",
    key: "examEndT"
  },
  {
    title: "操作",
    key: "action",
    scopedSlots: { customRender: "action" }
  }
];

const data = [];
const m = new Map();
export default {
  data() {
    return {
      markName: "", // 模糊查询
      previewVisible: false,
      previewImage: "",
      spinning: false,
      delayTime: 500,
      data,
      columns,
      idx: 0,
      form: {},
      list: [],
      examVisible: false,
      paper: {}
    };
  },
  methods: {
    handleCancel() {
      this.previewVisible = false;
    },
    showImg(url) {
      this.previewImage = url;
      this.previewVisible = true;
    },
    showMarkingModal(record) {
      this.spinning = true;
      this.list = [];
      this.paperid = record.examPaperId;
      this.paper = {};
      this.form = {};
      this.getExaminationByEid(record.id);
      this.examVisible = true;
    },
    getExaminationList() {
      this.$axios
        .get("/get/exam", {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            this.data = res.data.data;
            var obj;
            for (let i = 0; i < this.data.length; i++) {
              this.data[i].key = this.data[i].id;
              this.data[i].name = this.data[i].examName;
              obj = JSON.parse(this.data[i].examSetting);
              this.data[i].obj = obj;
              this.data[i].examClasses = obj[0].examClasses;
              this.data[i].examStartT = this.formDate(obj[0].examStartTime);
              this.data[i].examEndT = this.formDate(obj[0].examEndTime);
              this.data[i].examTotalScore = obj[0].examTotalScore;
            }
          } else {
            this.$message.error("获取失败");
          }
        });
    },
    formDate(dateForm) {
      if (dateForm === "") {
        //解决deteForm为空传1970-01-01 00:00:00
        return "";
      } else {
        var dateee = new Date(dateForm).toJSON();
        var date = new Date(+new Date(dateee) + 8 * 3600 * 1000)
          .toISOString()
          .replace(/T/g, " ")
          .replace(/\.[\d]{3}Z/, "");
        return date;
      }
    },
    getExaminationQuestion(paperId) {
      this.$axios
        .get("/get/testes/info/" + paperId, {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            this.paper = JSON.parse(res.data.data.testQuestions);
            this.dealWithData();
          } else {
            this.$message.error("获取失败");
          }
        });
    },
    getExaminationByEid(id) {
      this.$axios
        .get("/get/examData/finished/" + id, {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            this.form = res.data.data;
            console.log("original:", res.data.data);
            this.getExaminationQuestion(this.paperid);
          } else {
            this.$message.error("获取失败");
          }
        });
    },
    dealWithData() {
      if (this.form.length == 0) {
        this.spinning = false;
        return;
      }
      console.log("paper:", this.paper);
      console.log("original:", this.form);
      // 1. 把form转换一下
      for (let i = 0; i < this.form.length; i++)
        this.form[i].data = JSON.parse(this.form[i].data);
      // 2. 哈希表存每道题的内容
      for (let i = 0; i < this.paper.length; i++) {
        this.paper[i].questionImgs = this.paper[i].questionImg.split(",");
        m.set(this.paper[i].qid, this.paper[i]);
      }
      // 2. 处理每个人的数据
      for (let i = 0; i < this.form.length; i++)
        for (let j = 0; j < this.form[i].data.length; j++)
          if (
            this.form[i].data[j].answer == "" &&
            this.form[i].data[j].score == undefined
          ) {
            console.log(this.form[i].data[j]);
            this.list.push({
              i: i,
              j: j,
              qid: this.form[i].data[j].id,
              answer: this.form[i].data[j].keys,
              info: m.get(this.form[i].data[j].id)
            });
          }
      // 3. 获取考试使用的题库
      console.log("form-data:", this.form);
      console.log("list:", this.list);
      this.spinning = false;
    },
    postMark() {
      this.examVisible = false;
      if (this.list.length == 0) return;
      for (let i = 0; i < this.form.length; i++) {
        let score = 0;
        for (let _ = 0; _ < this.list.length; _++) {
          if (
            this.list[_].i == i &&
            this.form[this.list[_].i].data[this.list[_].j].score >= 0
          )
            score += this.form[this.list[_].i].data[this.list[_].j].score;
        }
        this.form[i].objectScore += score;
        this.form[i].data = JSON.stringify(this.form[i].data);

        this.$axios
          .put("/update/examData/marking", this.form[i], {
            headers: {
              Authorization: localStorage.getItem("token")
            }
          })
          .then(res => {
            if (res.data.code == 200) {
              this.$message.success("阅卷成功");
            } else {
              this.$message.error("阅卷失败");
            }
          });
      }
    },
    findMarkPaper() {
      if (this.markName.match(/^[ ]*$/)) {
        return this.$message.error("不能为空");
      }
      if (this.markName.replace(/(^s*)|(s*$)/g, "").length == 0) {
        this.getExaminationList();
        return;
      }
      this.$axios
        .get("/find/exam/names/" + this.markName, {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            this.data = res.data.data;
            var obj;
            for (let i = 0; i < this.data.length; i++) {
              this.data[i].key = this.data[i].id;
              this.data[i].name = this.data[i].examName;
              obj = JSON.parse(this.data[i].examSetting);
              this.data[i].obj = obj;
              this.data[i].examClasses = obj[0].examClasses;
              this.data[i].examStartT = this.formDate(obj[0].examStartTime);
              this.data[i].examEndT = this.formDate(obj[0].examEndTime);
              this.data[i].examTotalScore = obj[0].examTotalScore;
            }
          } else {
            this.$message.error(res.data.msg);
          }
        });
    }, // 重置搜索
    resetSearch() {
      this.markName = "";
      this.getExaminationList();
    }
  },
  created() {
    this.getExaminationList();
  }
};
</script>

<style scoped>
.notice {
  color: #1890ff;
  font-size: 16px;
  padding-top: 16px;
}
.icon-32 {
  font-size: 32px;
  color: #1890ff;
}
.title {
  margin-top: 10px;
  font-size: 16px;
}
.description {
  font-size: 12px;
  color: #7d8184;
}
.ant-card-grid-hoverable:hover {
  position: relative;
  z-index: 1;
  /* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15); */
  background: #e2f0ff;
}
.ant-card-grid {
  box-shadow: 0 0 0 0 #fff;
  display: block;
  cursor: pointer;
}
#components-layout-demo-basic {
  text-align: center;
}
#components-layout-demo-basic .ant-layout-header,
#components-layout-demo-basic .ant-layout-footer {
  background: #fff;
  color: #000;
}
#components-layout-demo-basic .ant-layout-footer {
  line-height: 1.5;
}
#components-layout-demo-basic .ant-layout-sider {
  background: #fff;
  color: #000;
  line-height: 120px;
}
#components-layout-demo-basic .ant-layout-content {
  background: #fff;
  color: #000;
  min-height: 120px;
  line-height: 120px;
}
#components-layout-demo-basic > .ant-layout {
  margin-bottom: 48px;
}
#components-layout-demo-basic > .ant-layout:last-child {
  margin: 0;
}
.media-content {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  border: 0;
  border-radius: inherit;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: 50% 50%;
  background-color: rgba(120, 120, 120, 0.1);
}
.media {
  position: relative;
  display: block;
  overflow: hidden;
  padding: 0;
  -ms-flex-negative: 0;
  -webkit-flex-shrink: 0;
  flex-shrink: 0;
  border-radius: inherit;
}
.questionImg {
  border-radius: 10px;
  margin-right: 10px;
  margin-top: 10px;
}
.tag-green {
  background-color: rgb(135, 208, 104);
}
</style>
